package io.gitee.chearnee.fw.openapi.processor;

import io.gitee.chearnee.fw.openapi.business.BusinessManager;
import io.gitee.chearnee.fw.openapi.business.entity.Application;
import io.gitee.chearnee.fw.openapi.business.entity.AuthorizedResources;
import io.gitee.chearnee.fw.openapi.cache.ICacheManager;
import io.gitee.chearnee.fw.openapi.config.OpenApiProperties;
import io.gitee.chearnee.fw.openapi.model.TokenResponse;
import io.gitee.chearnee.fw.openapi.utils.TokenUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author cn
 * @version 1.0
 * @description
 * @date 2021/9/23 21:40
 */
@Component
@AllArgsConstructor
public class OpenApiProcessor {

  private final BusinessManager businessManager;
  private final ICacheManager iCacheManager;
  private final OpenApiProperties openApiProperties;
  private final TokenUtil tokenUtil;

  public TokenResponse refreshToken(String appId) {
    Application application = businessManager.getApplicationByAppid(appId);
    String accessToken = tokenUtil.produceToken(application.getAppId(), application.getAppKey());
    long expiredIn = openApiProperties.getTokenExpirationTimeOut().getSeconds();
    LocalDateTime expiredTime = LocalDateTime.now()
        .plusSeconds(expiredIn);
    businessManager.updateApplicationTokenByAppId(application.getAppId(), accessToken, expiredTime);
    refreshAuthResource(appId);
    iCacheManager.saveCacheToken(appId, accessToken);
    return new TokenResponse(accessToken, expiredIn);
  }

  public void refreshAuthResource(String appId) {
    List<AuthorizedResources> authorizedResources = businessManager
        .listAuthorizedResources(appId);
    if (!authorizedResources.isEmpty()) {
      iCacheManager.refreshAuthResource(appId, authorizedResources);
    }
  }
}
